/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package srtp;

import TransportLayer.ISrtp;
import TransportLayer.SrtpException;
import cryptography.IKeyGenerator;
import cryptography.ISaltGenerator;
import platform.TenorPlatform;
import platform.TenorSrtpPacket;
import zorg.SRTP;

/**
 *
 * @author Tomasz Nowak
 */
public class SceneSrtp implements ISrtp
{
	private SRTP srtp;
	private ISaltGenerator saltGenerator;
	private IKeyGenerator keyGenerator;
	private int sequenceNumber;
	private int ssrc;

	public SceneSrtp( ISaltGenerator saltGenerator_, IKeyGenerator keyGenerator_, int ssrc_ ) throws SrtpException
	{
		saltGenerator = saltGenerator_;
		keyGenerator = keyGenerator_;

		srtp = new SRTP(new TenorPlatform());
		srtp.setRxMasterSalt(saltGenerator.generateSalt());
		srtp.setTxMasterSalt(saltGenerator.generateSalt());

		srtp.setRxMasterKey(keyGenerator.generateKey());
		srtp.setTxMasterKey(keyGenerator.generateKey());

		sequenceNumber = 1;
		ssrc = ssrc_;

		if ( srtp.startNewSession() != SRTP.SESSION_OK )
		{
			throw new SrtpException("starting session");
		}
	}

	public byte[] makePacket( byte[] message )
	{
		int date = 0x12345678;
		return srtp.protect(new TenorSrtpPacket(sequenceNumber++, date, ssrc, message)).getPacket();
	}

	public byte[] extractMessage( byte[] packet )
	{
		TenorSrtpPacket srtpPacket = new TenorSrtpPacket(packet);
		if ( srtp.unprotect(srtpPacket) != SRTP.UNPROTECT_OK )
		{
			return null;
		}
		else
		{
			byte[] result = new byte[srtpPacket.getPayloadLength()];
			System.arraycopy(srtpPacket.getPacket(), srtpPacket.getHeaderLength(), result, 0, srtpPacket.getPayloadLength());
			return result;
		}
	}

	private void setRxSalt( byte[] salt )
	{
		srtp.setRxMasterSalt(salt);
	}

	private void setTxSalt( byte[] salt )
	{
		srtp.setTxMasterSalt(salt);
	}

	private void setRxKey( byte[] key )
	{
		srtp.setRxMasterKey(key);
	}

	private void setTxKey( byte[] key )
	{
		srtp.setTxMasterKey(key);
	}
}
